#region Copyright Notice
/*
Copyright (C) 2011 by Ashley Ross

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion Copyright Notice

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;

namespace Manta.IO {
    /// <summary>
    /// Implements the ReparseDataBuffer struct.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class ReparseDataBuffer : IReparseDataBuffer {
        // * Reparse point tag. Must be a Microsoft reparse point tag.
        private ReparseTag _reparseTag;
        // * Size, in bytes, of the fields marked #.
        private ushort _reparseDataLength;
        // * Reserved; do not use. :)
        private ushort _reserved;
        // # Offset, in bytes, of the substitute name string in the PathBuffer array.
        private ushort _substituteNameOffset;
        // # Length, in bytes, of the substitute name string. If this string is NULL-terminated, SubstituteNameLength does not include space for the UNICODE_NULL character.
        private ushort _substituteNameLength;
        // # Offset, in bytes, of the print name string in the PathBuffer array.
        private ushort _printNameOffset;
        // # Length, in bytes, of the print name string. If this string is NULL-terminated, PrintNameLength does not include space for the UNICODE_NULL character. 
        private ushort _printNameLength;
        // # A buffer containing the unicode-encoded path string. The path string contains the substitute name string and print name string.
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = MaximumBufferSize)]
        private byte[] _pathBuffer;


        // Size, in bytes, of the fields marked *
        private const int HeaderSize = 8;
        // Size, in bytes, of the fields marked #, except _pathBuffer
        private const int MountPointHeaderSize = 8;
        // Maximum size, in bytes, of the _pathBuffer field
        private const int MaximumBufferSize = 0x3FF0;


        /// <summary>
        /// Initializes a new instance of the ReparseDataBuffer class.
        /// </summary>
        public ReparseDataBuffer() {
            _pathBuffer = new byte[MaximumBufferSize];
        }

        /// <summary>
        /// Initializes a new instance of the ReparseDataBuffer class with the specified reparse tag.
        /// </summary>
        /// <param name="tag">The reparse tag to initialize the ReparseDataBuffer with.</param>
        public ReparseDataBuffer(ReparseTag tag)
            : this() {
            _reparseTag = tag;
        }

        /// <summary>
        /// Initializes a new instance of the ReparseDataBuffer class with the specified reparse tag.
        /// </summary>
        /// <param name="tag">The reparse tag to initialize the ReparseDataBuffer with.</param>
        public ReparseDataBuffer(uint tag)
            : this((ReparseTag) tag) {
        }


        /// <summary>
        /// Gets or sets the reparse tag of the current ReparseDataBuffer.
        /// </summary>
        public ReparseTag Tag {
            get { return _reparseTag; }
            set { _reparseTag = value; }
        }

        /// <summary>
        /// Gets or sets the substitute name of the current ReparseDataBuffer.
        /// </summary>
        public string SubstituteName {
            get { return GetSubstituteFromPathBuffer(); }
            set { UpdatePathBuffer(value ?? string.Empty, GetPrintFromPathBuffer()); }
        }

        /// <summary>
        /// Gets or sets the print name of the current ReparseDataBuffer.
        /// </summary>
        public string PrintName {
            get { return GetPrintFromPathBuffer(); }
            set { UpdatePathBuffer(GetSubstituteFromPathBuffer(), value ?? string.Empty); }
        }

        /// <summary>
        /// Gets the size, in bytes, of the current ReparseDataBuffer.
        /// </summary>
        public int Size {
            get { return HeaderSize + _reparseDataLength; }
        }


        private string GetSubstituteFromPathBuffer() {
            if (_substituteNameLength == 0)
                return string.Empty;

            return Encoding.Unicode.GetString(_pathBuffer, _substituteNameOffset, _substituteNameLength) ?? string.Empty;
        }

        private string GetPrintFromPathBuffer() {
            if (_printNameLength == 0)
                return string.Empty;

            return Encoding.Unicode.GetString(_pathBuffer, _printNameOffset, _printNameLength) ?? string.Empty;
        }

        private void UpdatePathBuffer(string substitute, string print) {
            int substituteBytes = Encoding.Unicode.GetByteCount(substitute);
            int printBytes = Encoding.Unicode.GetByteCount(print);
            int nullCharSize = sizeof(char);
            int totalBytes = substituteBytes + nullCharSize + printBytes + nullCharSize;

            if (totalBytes > MaximumBufferSize)
                throw new PathTooLongException();

            // Set the offset and length fields, positioning the substitute name first.
            _substituteNameOffset = 0;
            _substituteNameLength = (ushort) substituteBytes;
            _printNameOffset = (ushort) (substituteBytes + nullCharSize);
            _printNameLength = (ushort) printBytes;

            // Convert the names to an array of bytes and insert it into the path buffer
            Array.Clear(_pathBuffer, 0, _pathBuffer.Length);
            Encoding.Unicode.GetBytes(substitute, 0, substitute.Length, _pathBuffer, 0);
            Encoding.Unicode.GetBytes(print, 0, print.Length, _pathBuffer, _printNameOffset);

            // Update the reparse data length 
            _reparseDataLength = (ushort) (MountPointHeaderSize + totalBytes);
        }
    }
}